package app.io;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.List;

import app.system.KBFileFilter;

import kb.DescriptionLogicsKB;

import utils.io.KBAccess;
import utils.io.QueryAccess;

public class LoadWebFile {

	private String is;
	private boolean queryfile;
	private List<Object[]> querylines;
	private DescriptionLogicsKB kb;
	
	public LoadWebFile(String urlAddr, boolean queryFile){
		this.is = urlAddr;
		this.queryfile = queryFile;
	}
	
	public List<Object[]> getQueries(){
		if(this.queryfile){
			return this.querylines;
		}else{
			System.err.println("The URL "+this.is +"represents NOT a query file. Null returned.");
		}
		return null;
	}
	
	public DescriptionLogicsKB getKB(){
		if(! this.queryfile){
			return this.kb;
		}else{
			System.err.println("The URL "+this.is +"represents NOT a KB. Null returned.");
		}
		return null;
	}
	
	public boolean resolveFile(){
		URL url = this.resolveURL();
		String fp = url.getFile();
		if(fp.trim().equals("")){
			System.err.println("The given URL does not represent any file.");
			return false;
		}else{
			String ext = fp.substring(fp.lastIndexOf('.')+1);
			if(! KBFileFilter.ds.keySet().contains(ext)){
				System.err.println("The file format is not recognized by our system.");
				return false;
			}
		}
		try {
			URLConnection loc = url.openConnection();
			InputStream stream = loc.getInputStream();
			BufferedReader in = new BufferedReader(
                    new InputStreamReader(stream));
			if(this.queryfile){
				//a query file is being retrieved, store a copy.
				querylines = QueryAccess.getQueries(in, null);
			}else{
				//get the knowledge base
				this.kb = KBAccess.processKBFile(in, false);
			}
		} catch (FileNotFoundException e) {
			System.err.println("No such file exists, please check your URL: "+url);
			return false;
		} catch(IOException e){
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	private URL resolveURL(){
		//the default protocol is the first one
		String[] protocols = {"http:", "HTTP:", "ftp:", "FTP:"};
		is = is.trim();
		try {
			is = URLDecoder.decode(is, "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		int id = is.indexOf("//");
		if(id < 0){
			is = protocols[0] +"//" + is;
		}else{
			String pc = is.substring(0, id);
			if(! Arrays.asList(protocols).contains(pc)){
				System.err.println("Unsupported protocol in the URL, replaced by \'http\': "+pc);
			}
		}
//		try {
//			is = java.net.URLEncoder.encode(is, "UTF-8");
//		} catch (UnsupportedEncodingException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		URL ret = null;
		try {
			ret = new URL(is);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ret;
	}
	
}
